using MyFramework.Resource;
using MyFramework.Singleton;
using UnityEngine;

namespace MyFramework.Audio
{
    public class AudioManager : Singleton<AudioManager>
    {
        private AudioSource _bgmAudioSource;

        private float _volume = 1;
        public float Volume
        {
            get => _volume;
            set
            {
                if (value is >= 0 and <= 1)
                    _volume = value;
                else
                    Debug.LogWarning("音量设置错误");
            }
        }

        private bool BGMIsNull()
        {
            return !_bgmAudioSource;
        }

        /// <summary>
        /// 播放背景音乐
        /// </summary>
        /// <param name="path">背景音乐文件路径</param>
        public void PlayBgm(string path)
        {
            if (BGMIsNull())
            {
                GameObject obj = new GameObject("Background Music");
                _bgmAudioSource = obj.AddComponent<AudioSource>();
            }

            ResourcesManager.GetInstance().LoadAsync<AudioClip>(path, clip =>
            {
                _bgmAudioSource.clip = clip;
                _bgmAudioSource.volume = _volume;
                _bgmAudioSource.Play();
            });
        }

        public void ChangeBgmVolume(float volume)
        {
            this._volume = volume;

            if (BGMIsNull())
                return;

            _bgmAudioSource.volume = this._volume;
        }

        /// <summary>
        /// 暂停背景音乐
        /// </summary>
        public void PauseBgm()
        {
            if (BGMIsNull())
                return;
            _bgmAudioSource.Pause();
        }

        /// <summary>
        /// 停止背景音乐
        /// </summary>
        public void StopBgm()
        {
            if (BGMIsNull())
                return;
            _bgmAudioSource.Stop();
        }

        /// <summary>
        /// 播放音效
        /// </summary>
        /// <param name="soundName">音效文件名</param>
        public void PlaySound(string soundName)
        {

        }

        /// <summary>
        /// 停止音效
        /// </summary>
        /// <param name="soundName">音效文件名</param>
        public void StopSound(string soundName)
        {

        }
    }
}
